import {fetch} from '../../../utils/axios'
import {downExcel} from '../../../utils/common'

const state = {
  name: '网络资源列表',
  editdialog: false,
  id: null,
  search: '',
  totalItems: 0,
  items: [],
  loading: true,
  pagination: {},
  headers: [],
  etext: 'No Data',
  rowsPerPageItems: [10, 50, 100, { text: 'All', value: 100000 }],
  searchLabel: 'ip'
}

const mutations = {
  handlerIps: (state) => {
    const { sortBy, descending, page, rowsPerPage } = state.pagination
    let ordering = descending ? '-' + sortBy : sortBy
    fetch('/ips/', {
      offset: (page - 1) * rowsPerPage,
      limit: rowsPerPage,
      ordering,
      search: state.search
    }).then((response) => {
      state.items = response.results
      state.totalItems = response.count
      state.loading = false
    }).catch((error) => {
      state.etext = error.response
    })
  },
  ipsDownload () {
    downExcel(state.headers, state.items)
  },
  openIpsEdit (state, payload) {
    state.id = payload.id
    state.editdialog = true
  },
  loadIpsHeaders (state) {
    fetch('/getmodels/', {
      appname: 'ips',
      modelname: 'OutterIpSource'
    }).then((response) => {
      state.headers = JSON.parse(response)
      state.headers.splice(7, 0, {text: '状态', align: 'center', value: 'status', sortable: false})
    }).catch((error) => {
      state.etext = error.response
    })
  }
}

const actions = {
  handlerIps: ({commit}) => {
    state.loading = true
    commit('handlerIps')
  },
  ipsDownload ({commit}) {
    commit('ipsDownload')
  },
  openIpsEdit ({commit}, payload) {
    commit('openIpsEdit', payload)
  },
  loadIpsHeaders ({commit}) {
    commit('loadIpsHeaders')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
